/*******************************************************
 * @Title: LogInterceptor
 * @ProjectName: AgileFastFK2.5
 * @Package: com.caltco.cargo.ops.interceptor
 * @Description: TODO
 * @author: daixirui
 * @version: V1.0.0
 * @Copyright: 2021 All rights reserved.
 * @date 2021/10/14 10:23</br>
 ********************************************************
 * @date 2021/10/14 10:23
 * @Title: 创建类
 * @version V1.0.0
 * @Description: TODO
/******************************************************/
package com.caltco.cargo.ops.common.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.UUID;

@Component
public class LogInterceptor implements HandlerInterceptor {
    /**
     * 会话ID
     */
    private final static String LOG_SESSION_KEY = "logsessionId";


    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                           Object arg2, ModelAndView arg3) throws Exception {
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {

        String token = request.getSession().getId();
        String uuid= UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        uuid=uuid.substring(uuid.length()-8,uuid.length());
        MDC.put(LOG_SESSION_KEY, uuid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0,
                                HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // 删除
        MDC.remove(LOG_SESSION_KEY);
    }
}